import storage from '@/utils/storage'
import setting from '@/settings'

export default {
  // 设置token，以及标记已登录的标识
  setToken(state, params) {
    state.tokenName = params.tokenName;
    state.tokenValue = params.tokenValue;
    storage.set(setting.tokenName, true);
  },
  // 退出登录 - 删除登录信息
  loginOut(state) {
    state.tokenName = null;
    state.tokenValue = null;
    state.currentInfo = null;
    state.currentTenant = null;
    storage.set(setting.tokenName, false);
  },
  // 切换用户的企业
  switchUserTenant(state, currentTenant) {
    state.currentTenant = currentTenant;
  },
  // 执行筛选租户信息 (若有审核通过的，则设置审核通过的作为当前展示，若无则取第一条展示)
  doFilterUserTenants(state) {
    let tenants = state.currentInfo ? state.currentInfo.tenants : [];
    if (tenants.length === 0) {
      this.commit('user/loginOut');
      return;
    }
    let currentTenant = state.currentTenant;
    if (tenants.length > 0) {
      let hasTenant = false;
      if(currentTenant) {
        for (let item of tenants) {
          if (item.id === currentTenant.id) {
            hasTenant = true;
            currentTenant = item;
            break;
          }
        }
      }

      if (!hasTenant) {
        currentTenant = tenants[0];
      }

      if (Number(currentTenant.auditStatus) !== 2) {
        for (let item of tenants) {
          if (Number(item.auditStatus) === 2) {
            currentTenant = item;
            break;
          }
        }
      }
    }

    if(state.currentTenant && currentTenant) {
      let isEqual = true;
      for(let key in currentTenant) {
        if(state.currentTenant[key] !== currentTenant[key]) {
          isEqual = false;
          break;
        }
      }
      if(!isEqual)
        state.currentTenant = currentTenant;
    } else {
      state.currentTenant = currentTenant;
    }
  }
}
